package com.wdciti.sccp.iot.gateway.endpoint.my;

import com.wdciti.sccp.iot.springvertx.annotation.VerticleBean;
import com.wdciti.sccp.iot.gateway.domain.Channel;
import com.wdciti.sccp.iot.gateway.domain.PersonTagBind;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.LocalMap;
import io.vertx.ext.web.client.WebClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

/**
 * @Author xxing
 * @Description 人员定位卡绑定
 * @Date 2023/7/18
 **/
@Slf4j
@VerticleBean(isWorker = false)
public class PersonTagBindVerticle extends AbstractVerticle {

    @Value("${plat.personTagBindUrl}")
    private String personTagBindUrl;

    @Override
    public void start() {
        LocalMap<String, JsonObject> personTagCache = vertx.sharedData().getLocalMap("personTagList");

        vertx.setPeriodic(10*1000, 600*1000, hd -> {
            WebClient webClient = WebClient.create(vertx);
            webClient.getAbs(personTagBindUrl).send().onSuccess(response -> {

                personTagCache.clear();
                vertx.sharedData().getLocalMap(PersonTagBind.whiteListPrefix() + Channel.mex.name()).clear();
                if (response.statusCode() != 200 || response.bodyAsJsonObject().getInteger("code") != 200) {
                    String msg = response.bodyAsJsonObject().getString("msg");
                    log.error("personTagBindUrl服务报错！msg:{}, url={}", msg, personTagBindUrl);
                    return;
                }
                JsonArray array = response.bodyAsJsonObject().getJsonArray("data");
                log.info("标签人员绑定数量为：{}",array.size());
                for (int i = 0; i < array.size(); i++) {
                    JsonObject data = array.getJsonObject(i);
                    PersonTagBind personTagBind = data.mapTo(PersonTagBind.class);
                    JsonObject tagBinds = personTagCache.getOrDefault(personTagBind.getPersonId(),JsonObject.of()); //p_122131111
                    tagBinds.put(personTagBind.getChannel(), data);
                    personTagCache.put(personTagBind.getPersonId(), tagBinds);
                    String whiteListCache = PersonTagBind.whiteListPrefix() + personTagBind.getChannel(); //white_mex
                    LocalMap<String, JsonObject> whiteList = vertx.sharedData().getLocalMap(whiteListCache);
                    if(personTagBind.getTargetId()!=null){
                        whiteList.put(personTagBind.getTargetId(), data);
                    }
                }

//                vertx.sharedData().getLocalMap("personTagList");
            }).onFailure(Throwable::printStackTrace);
        });
    }


}
